package org.jsonstruts.filter;

import java.io.PrintWriter;
import java.util.Enumeration;




import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsonstruts.spring.ApplicationSupport;
import org.jsonstruts.utils.JSONCommon;
import org.jsonstruts.utils.ReflectUtils;

public class Execute
{
	 
	@SuppressWarnings("unchecked")
	public static void handle(HttpServletRequest request,String str,HttpServletResponse response)
	{    
		Object target=null;
		try
		{     
			    if( ApplicationSupport.IS_SPRING_ENABLED){ 
				target= ApplicationSupport.getTarget(str);
			    }
			    else{
			    target=Class.forName(str).newInstance();
			    }
				Enumeration<String> enumration=request.getParameterNames();
				while(enumration.hasMoreElements())
				{
					String paramName=enumration.nextElement();
					String paramValue=request.getParameter(paramName);
					ReflectUtils.setValue(target,paramName,paramValue);
				}
				
			 
			
		} catch (Exception e)
		{ 
			e.printStackTrace();
		}
		finally
		{   
			 Object obj=ReflectUtils.invoke(target, "execute");
			 if(obj!=null)
			 {
				 try
				{
					write(response,obj);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			 }
			 request=null;
			 response=null;
		}
	}
    
	private final static  void write(HttpServletResponse resp,Object obj) throws Exception
	{
		    resp.setContentType("text/plain;charset=UTF-8");
	        resp.setCharacterEncoding("utf-8");
	        PrintWriter out =resp.getWriter();
	        writeObj(out,obj);
	        out.flush();
	        out.close();
	        out=null;
	}
	
	private final static void writeObj(PrintWriter out,Object obj)
	{
		 if(obj.getClass().isPrimitive()||obj instanceof String)
	        {
	        	 out.write(obj.toString());
	        }
	        else
	        {
	        	 JSONCommon common=new JSONCommon();
	        	 out.write(common.BeanToJSON(obj));
	        }
	}
}
